package pres.liko.iot.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import pres.liko.iot.api.CacheOpenfrignClient;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: CacheConfig
 * @Auther: liko
 * @Description:
 * @Date: 2022/11/2 09:03
 */
// @Component
@EnableAsync//开启异步
public abstract class BaseCacheConfig<E> {

    @Autowired
    private CacheOpenfrignClient cacheOpenfrignClient;

    private Set<String> blackCache = new HashSet<>();
    private AtomicInteger atomicInteger = new AtomicInteger(1);
    private boolean isInit;

    public Set<String> getBlackcache() {
        return blackCache;
    }

    // @PostConstruct
    public void init() {
        // 加载黑名单
        cacheOpenfrignClient.sget(getCacheKey())
                .subscribe(strings -> {
                    // 清除ips
                    blackCache.clear();
                    // 将新数据统一添加
                    blackCache.addAll(strings);
                });

    }

    @EventListener
    @Async//异步执行
    public void onStartUp(ContextRefreshedEvent event) {
        // 容器会加载两次，一次是父容器（spring） ,一次是子容器(Spring MVC)
        // 通过线程安全的数字来记录操作此时
        int num = atomicInteger.getAndIncrement();
        if (num == 1) {
            System.out.println("系统启动时候的初始化" + getClass().getName());
            // isInit = true; //定义全局变量
            init();
        }
    }

    @EventListener
    @Async
    public void onEventUpdate(E event) {
        init();
    }

    protected abstract String getCacheKey();
}
